from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import JsonResponse
from apps.areas.models import Area


class AreaView(View):
    """获取省份信息"""

    def get(self, request):
        province_list = cache.get('province')
        if province_list is None:
            # 获取省份信息
            provinces = Area.objects.filter(parent=None)
            # 需要将获取到的对象数据转换为字典数据
            province_list = []
            for province in provinces:
                province_list.append({
                    'id': province.id,
                    'name': province.name
                })
            cache.set('province', province_list, 60 * 60 * 24)
        return JsonResponse({
            'code': 0,
            'errmsg': '查询省份信息成功',
            'province_list': province_list
        })


class SubsAreaView(View):
    """获取对应省份的市区信息"""
    def get(self, request, id):
        # data_list = cache.get('city:%s' % id)
        # if data_list is None:
            father = Area.objects.get(id=id)
            son = father.subs.all()
            data_list = []
            for msg in son:
                data_list.append({
                    'id': msg.id,
                    'name': msg.name
                })

            sub_data = {
                'id': father.id,  # 父级pk
                'name': father.name,  # 父级name
                'subs': data_list  # 父级的子集
            }
            # cache.set('city:%s' % id, data_list, 3600 * 24)
            return JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'sub_data': sub_data
            })
